package com.lzx.dormsys.util.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * Jwt加密和解密
 */
public class JwtToken {
    private static String secret = "abcdefghijklmnopqrstuvwxyz";
    private static long expire = 120*60*4L* 1000;
    private static String header = "Authorization";

    /**
     * 生成jwt token
     */
    public String generateToken(String json) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire);

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;    //把一段文件信息进行加密，产生加密字符串，并且设置过期时间

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(json)//被加密的字符串 （登录用户信息）
                .setIssuedAt(nowDate)//当前系统 时间
                .setExpiration(expireDate)   //过期时间
                .signWith(signatureAlgorithm, secret.getBytes())  // new String(org.apache.commons.codec.binary.Base64.encodeBase64(secret.getBytes()) 把密钥用Base64加密
                .compact();


//        .signWith(SignatureAlgorithm.HS512, secret)
//        .compact();
    }


    private Claims getClaimByToken(String access_token) { //把generateToken产生的字符串进行解密,得到Claims对象
        String token = access_token.split("Bearer ")[1];

        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
            return Jwts.parser()
                    .setSigningKey(secret.getBytes())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            System.out.println("jwt 解密失败"+e);
//            e.printStackTrace();
            return null;
        }
    }

    public String getLoginUserInfo(HttpServletRequest request) throws AuthenticationException {

        String access_token = request.getHeader(header);

        if (access_token == null || "".equals(access_token)) {
            throw new AuthenticationException("客户端在请求头中未传递access_token值");
        }

        Claims claims = getClaimByToken(access_token);//jwtToken.getClaimByToken(access_token);


        if (JwtToken.isTokenExpired(claims.getExpiration())) {
            throw new AuthenticationException("access_token 过期");
        }


        String tokenVal = claims.getSubject();//得到登录用户信息(Json字符串)

        return tokenVal;
    }
    /*public Claims getClaimByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        String[] header = token.split("Bearer");
        token = header[1];
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }*/

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    // Getter && Setter
}